import React, { Component } from 'react';
import {
  Input,
  Form,
  Button,
  Checkbox,
  Switch,
  Dropdown,
  Space,
  Badge,
  Table,
  DatePicker,
  message,
} from 'antd';
import { UserOutlined, LockOutlined, DownOutlined } from '@ant-design/icons';
import moment from 'moment';
const uploadKey = 'uploadKey';

export default class Login extends Component {
  // 得到强大的form实体、有验证、有获取数据等等
  formRef = React.createRef();
  state = {
    render: false,
  };

  onFinish = (event) => {
    message.success({
      content: 'Loaded!',
      uploadKey,
      duration: 2,
    });
    console.log(this.formRef.current.validateFields()); //验证方法三，也是页面拿到数据后的处理操作，也可以进行检验，新版本返回的是promise
    this.formRef.current
      .validateFields()
      .then((value) => {
        // 验证通过后进入
        console.log(value);
      })
      .catch((err) => {
        // 验证不通过时进入
        console.log(err);
      });
    console.log('Received values of form: ', event);
  };
  componentDidMount() {
    // message.loading({ content: '上传中，请稍后...', uploadKey, duration: 0 });
  }

  render() {
    const form = this.formRef.current;
    let user = [
      { name: 'User 1', age: 25 },
      { name: 'User 2', age: 30 },
      { name: 'User 3', age: 35 },
    ];
    const initialValues = {
      users: user,
    };
    const all = form == undefined ? false : form.getFieldValue('all');
    console.log('all-----', all);
    let prefix = 'mac,product_key,device_name,device_secret,product_secret,hid,language';
    var menuItems = [];
    menuItems = prefix.split(',');
    const items = [];

    menuItems.forEach((item) => {
      items.push({ key: item, label: item });
    });
    // const items = [
    //   {
    //     key: '1',
    //     label: '1',
    //   },
    //   {
    //     key: '2',
    //     label: 'Action 2',
    //   },
    // ];
    const expandedRowRender = () => {
      const columns = [
        {
          title: 'Date',
          dataIndex: 'date',
          key: 'date',
        },
        {
          title: 'Name',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: 'Status',
          key: 'state',
          render: () => (
            <span>
              <Badge status="success" />
              Finished
            </span>
          ),
        },
        {
          title: 'Upgrade Status',
          dataIndex: 'upgradeNum',
          key: 'upgradeNum',
        },
        {
          title: 'Action',
          dataIndex: 'operation',
          key: 'operation',
          render: () => (
            <Space size="middle">
              <a>Pause</a>
              <a>Stop</a>
              <Dropdown
                menu={{
                  items,
                }}
              >
                <a>
                  More <DownOutlined />
                </a>
              </Dropdown>
            </Space>
          ),
        },
      ];
      const data = [];
      for (let i = 0; i < 3; ++i) {
        data.push({
          key: i.toString(),
          date: '2014-12-24 23:12:00',
          name: 'This is production name',
          upgradeNum: 'Upgraded: 56',
        });
      }
      return <Table columns={columns} dataSource={data} pagination={false} />;
    };
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: 'Platform',
        dataIndex: 'platform',
        key: 'platform',
      },
      {
        title: 'Version',
        dataIndex: 'version',
        key: 'version',
      },
      {
        title: 'Upgraded',
        dataIndex: 'upgradeNum',
        key: 'upgradeNum',
      },
      {
        title: 'Creator',
        dataIndex: 'creator',
        key: 'creator',
      },
      {
        title: 'Date',
        dataIndex: 'createdAt',
        key: 'createdAt',
      },
      {
        title: 'Action',
        key: 'operation',
        render: () => <a>Publish</a>,
      },
    ];
    const data = [];
    for (let i = 0; i < 3; ++i) {
      data.push({
        key: i.toString(),
        name: 'Screem',
        platform: 'iOS',
        version: '10.3.4.5654',
        upgradeNum: 500,
        creator: 'Jack',
        createdAt: '2014-12-24 23:12:00',
      });
    }
    return (
      <div className="login">
        <header className="login-header">
          {/* <img src={logo} alt="图标加载失败" /> */}
          <h1>React 后台管理系统</h1>
        </header>
        <section className="login-content">
          <h2>用户登录</h2>

          {/* antd组件 */}
          <Form
            ref={this.formRef}
            name="normal_login"
            className="login-form"
            initialValues={initialValues}
            onFinish={this.onFinish}
          >
            <Form.Item
              label="是否启用公共字段"
              name={'all'}
              initialValue={false}
              style={{
                margin: '0 8px',
              }}
              valuePropName="checked"
            >
              <Switch
                checkedChildren="已开启"
                unCheckedChildren="已关闭"
                onChange={(check) => {
                  console.log(check);
                  this.formRef.current.setFieldsValue({ all: check });
                  this.setState({ render: check });
                }}
              />
            </Form.Item>
            <Form.Item
              label="mac数量、顺序"
              name={'mac'}
              initialValue={false}
              valuePropName="checked"
              shouldUpdate={(prevValues, curValues) => prevValues.all !== curValues.all}
            >
              <Switch disabled={all} />
            </Form.Item>
            {/* 用户名字 校验规则rules */}
            <Form.Item
              name="username"
              rules={[
                {
                  type: 'string',
                  required: true,
                  message: '请输入用户名!',
                  pattern: /\w+/,
                  whitespace: true,
                  max: 12,
                  min: 4,
                },
              ]}
            >
              <Input
                prefix={<UserOutlined className="site-form-item-icon" />}
                placeholder="Username"
              />
            </Form.Item>
            {/* 用户密码 */}
            <Form.Item
              name="password"
              rules={[
                {
                  type: 'string',
                  required: true,
                  message: '请输入密码!',
                  pattern: /\w+/,
                  whitespace: true,
                  max: 12,
                  min: 4,
                },
              ]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                placeholder="Password"
              />
            </Form.Item>
            {/* 用户密码确认 */}
            <Form.Item
              name="Confirmpassword"
              rules={[
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    console.log(getFieldValue('password'), value);
                    return Promise.reject(new Error('两次密码不匹配'));
                  },
                }),
              ]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="请再次输入Password"
              />
            </Form.Item>
            <Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>Remember me</Checkbox>
              </Form.Item>

              {/* <a className="login-form-forgot" href="">
                  Forgot password
                </a> */}
            </Form.Item>
            <Form.List name="users">
              {(fields, { add, remove }) => {
                return (
                  <div>
                    {fields.map((field, index) => (
                      <Form.Item {...field} label={`User ${index + 1}`} key={field.key}>
                        <Input value={`${user[index].name} ${JSON.stringify(fields)}`} />
                        <Input value={`${field.age} ${index}`} />
                      </Form.Item>
                    ))}
                    <Form.Item>
                      <Button type="dashed" onClick={() => add()} block>
                        Add field
                      </Button>
                    </Form.Item>
                  </div>
                );
              }}
            </Form.List>
            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button">
                Log in
              </Button>
              {/* Or <a href="">register now!</a> */}
            </Form.Item>
          </Form>
        </section>
        <Form.Item
          name="measureTime"
          label="测量时间"
          initialValue={moment('2020-09-04T09:17:19.340Z')}
          rules={[{ required: true, message: '请输入测量时间！' }]}
        >
          <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
        </Form.Item>
        <Table
          columns={columns}
          expandable={{
            expandedRowRender,
            defaultExpandedRowKeys: ['0'],
          }}
          dataSource={data}
        />
      </div>
    );
  }
}
